package com.liwenxu;

import android.app.Activity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.FrameLayout;

import com.Exception.ConnectException;
import com.Exception.startIPCameraException;
import com.Exception.tutkAPIException;
import com.tutk.IOTC.AVAPIs;
import com.tutk.IOTC.IOTCAPIs;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by 李文旭 on 2018/9/9.
 */

public class VideoPlay {
    private Activity context;
    public static SurfaceHolder se;
    public static byte[] mSps={0,0,0,1,103,77,0,31,-107,-88,20,1,110,-101,-128,-128,-128};
    public static byte[] mPps={0,0,0,1,104,-18,60,-128,0,0,0,1,6,-27,1,89,-128};
    public static BlockingQueue<framInfo> queue=new LinkedBlockingQueue<framInfo>();
    public static BlockingQueue<framInfo> AudioQueue=new LinkedBlockingQueue<framInfo>();
    public VideoPlay(Activity context,SurfaceHolder se)
    {
        this.context=context;
        this.se=se;
    }
    public void StartVideo(int camerIndex) throws ConnectException,startIPCameraException,tutkAPIException {
        Integer avchannelID=Connect.avchannelMap.get(camerIndex);
        if(avchannelID==null)
        {
            throw new ConnectException("连接设备失败,请重试",avchannelID);
        }
        if (startIpcamStream(avchannelID)) {
            Log.d("video thread "," ");
            Thread videoThread = new Thread(new VideoThread(avchannelID),
                    "Video Thread");
            videoThread.start();
            Thread audioThread=new Thread(new AudioThread(avchannelID));
            audioThread.start();
        }
        else
        {
            throw new startIPCameraException("摄像机启动失败，请重试",avchannelID);
        }
    }
    public static void check(int ready) throws tutkAPIException {
        if(ready<0)
        {
            throw new tutkAPIException("tutk的api没有返回0，而是返回了"+ready,ready);
        }
    }
    //Exception在哪里？？？？
    public static boolean startIpcamStream(int avIndex) throws tutkAPIException {
        AVAPIs av = new AVAPIs();
        int ret = av.avSendIOCtrl(avIndex, AVAPIs.IOTYPE_INNER_SND_DATA_DELAY,
                new byte[2], 2);
        check(ret);
        // This IOTYPE constant and its corrsponsing data structure is defined in
        // Sample/Linux/Sample_AVAPIs/AVIOCTRLDEFs.h
        //
        int IOTYPE_USER_IPCAM_START = 0x1FF;
        ret = av.avSendIOCtrl(avIndex, IOTYPE_USER_IPCAM_START,
                new byte[8], 8);
        check(ret);

        int IOTYPE_USER_IPCAM_AUDIOSTART = 0x300;
        ret = av.avSendIOCtrl(avIndex, IOTYPE_USER_IPCAM_AUDIOSTART,
                new byte[8], 8);
        check(ret);
        return true;
    }
}
